﻿using System;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Controls;

namespace Chenglin.WPJigsawPuzzle
{
    public partial class MainPage : PhoneApplicationPage
    {
        private GameState _gameState;

        /// <summary>
        /// Constructor
        /// </summary>
        public MainPage()
        {
            InitializeComponent();

            // Hook event handlers
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
            this.EasyModeButton.Tap += (sender, e) => { NavigateToGame(3); };
            this.NormalModeButton.Tap += (sender, e) => { NavigateToGame(4); };
            this.HardModeButton.Tap += (sender, e) => { NavigateToGame(5); };

            int imageCount = 0; // zero-based position
            for (int i = 0; i < PuzzleImagesPanel.Children.Count - 1; i++)
            {
                StackPanel panel = (StackPanel)PuzzleImagesPanel.Children[i];
                foreach (Image image in panel.Children)
                {
                    // Save the image position in its Tag property
                    //
                    image.Tag = imageCount++;

                    // Hook event handler
                    image.Tap += (sender, e) => { MarkSelectedImage((int)((Image)sender).Tag); };
                }
            }

            _gameState = GameState.State;
            if (_gameState.ImagePos < 0 || _gameState.ImagePos >= imageCount)
            {
                // Looks like we had an invalid state file...
                _gameState.ImagePos = 0;
            }
            MarkSelectedImage(_gameState.ImagePos);
        }

        private void NavigateToGame(int level)
        {
            Uri gamePage = new Uri(string.Format("/GamePage.xaml?level={0}&img={1}", level, (_gameState.ImagePos + 1)), UriKind.Relative);
            NavigationService.Navigate(gamePage);
        }

        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        { }

        private void MarkSelectedImage(int imgPos)
        {
            _gameState.ImagePos = imgPos;

            const int DoubleMargin = 10;
            const int ImageWidth = 128;
            const int NumImagePerLine = 3;

            int row = imgPos / NumImagePerLine;
            int column = imgPos % NumImagePerLine;

            // Ther marker panel will always be the last one in PuzzleImagesPanel
            //
            int markerRow = PuzzleImagesPanel.Children.Count - 1;

            MarkerTransform.X = (DoubleMargin + ImageWidth) * column;
            MarkerTransform.Y = (DoubleMargin + ImageWidth) * (row - markerRow);
        }
    }
}